﻿using Electric.Entity.AuditLogs;
using Electric.Entity.Users;
using Microsoft.AspNetCore.Identity;

namespace Electric.API.AuditLog
{
    public class AuditLogHelper
    {
        /// <summary>
        /// 请求日志
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="userManager"></param>
        /// <returns></returns>
        public static EleAuditLog GenerateRequestAuditLog(HttpContext httpContext, UserManager<EleUser> userManager)
        {
            //审核日志
            EleAuditLog auditLog = new EleAuditLog();
            var request = httpContext.Request;

            //当前用户
            var userName = httpContext.User.Identity.Name;
            if (!string.IsNullOrEmpty(userName))
            {
                var user = userManager.FindByNameAsync(userName).Result;
                auditLog.CreatorId = user.Id;
            }
            auditLog.ApiUrl = request.Path;
            auditLog.Method = request.Method;
            auditLog.AuditLogType = AuditLogType.Info;

            //ip
            var remoteIpAddress = httpContext.Connection.RemoteIpAddress;
            auditLog.ClientIpAddress = remoteIpAddress == null ? string.Empty : remoteIpAddress.MapToIPv4().ToString();
            auditLog.BrowserInfo = request.Headers.ContainsKey("User-Agent") ? request.Headers["User-Agent"] : string.Empty;
            if (request.Method == "GET")
            {
                auditLog.Parameters = request.QueryString.Value ?? string.Empty;
            }
            else
            {
                using (StreamReader reader = new StreamReader(request.Body))
                {
                    request.Body.Position = 0;
                    auditLog.Parameters = reader.ReadToEndAsync().Result;
                    request.Body.Position = 0;
                }
            }

            return auditLog;
        }
    }
}